<template>
  <view>
    <!-- 返回按钮 -->
    <button @click="goBackToFind">返回</button>

    <view class="question-context">{{ questionContext }}</view>

    <!-- 录音按钮 - 根据 test 属性禁用 -->
    <button
      @click="startRecording"
      :disabled="!isConnected || isRecording || isTextQuestion"
    >
      开始录音
    </button>
    <button @click="stopRecording" :disabled="!isRecording || isTextQuestion">
      停止录音
    </button>
    <text>录音状态：{{ isRecording ? "录音中" : "未录音" }}</text>

    <!-- 文本输入框和发送按钮 - 根据 test 属性启用 -->
    <textarea
      v-model="inputAnswer"
      placeholder="请输入代码文本内容"
      style="height: 100px"
      :disabled="!isTextQuestion"
    />
    <button
      @click="sendAnswer"
      :disabled="!isConnected || !inputAnswer || !isTextQuestion"
    >
      发送回答
    </button>

    <!-- 新增：后端消息显示区域 -->
    <view class="server-message-container">
      <text class="section-title">语音转写返回结果：</text>
      <scroll-view scroll-y class="message-content">
        {{ filteredServerMessage }}
      </scroll-view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isRecording: false,
      mediaRecorder: null,
      audioChunks: [],
      socket: null,
      isConnected: false, // 新增用于标识 WebSocket 是否已连接
      audioBuffer: new Uint8Array(1280), // 每40ms发送1280字节
      bufferIndex: 0,
      audioContext: null,
      processor: null,
      inputInterviewId: "", // 输入框绑定值
      interviewId: "", // 确认后的ID
      questionOrder: "",
      inputAnswer: "",
      isFormConfirmed: false, // 新增确认状态
      interviewId: "", // 从参数获取
      questionOrder: "", // 从参数获取
      questionContext: "", // 问题内容
      isFormConfirmed: true, // 直接设置为true
      serverMessage: "", // 存储原始服务器消息
      filteredServerMessage: "", // 存储过滤后的消息
      isTextQuestion: false, // 新增：标识是否为文本题
    };
  },
  onLoad(options) {
    // 接收参数并赋值
    this.interviewId = options.interviewId || "";
    this.questionOrder = options.questionId || "";
    this.questionContext = decodeURIComponent(options.context || "");
    this.isTextQuestion = options.test === "true"; // 从参数获取 test 属性

    // 自动建立连接
    this.connectWebSocket();
  },
  computed: {
    isFormValid() {
      return this.inputInterviewId && this.inputQuestionOrder;
    },
  },
  methods: {
    goBackToFind() {
      uni.navigateTo({
        url: "/pages/index/find/find", // 确保路径与您的项目结构一致
      });
    },
    sendAnswer() {
      if (this.socket?.readyState === WebSocket.OPEN && this.inputAnswer) {
        const answerData = JSON.stringify({
          Answer: this.inputAnswer,
        });
        this.socket.send(answerData);
        console.log("已发送回答内容:", answerData);
        this.inputAnswer = ""; // 清空输入框
        uni.showToast({ title: "发送成功", icon: "success" });
        this.closeWebSocket();
      }
    },
    // 新增发送interviewId方法
    sendInitData() {
      if (this.socket?.readyState === WebSocket.OPEN) {
        const initData = JSON.stringify({
          interviewId: this.interviewId,
          questionOrder: this.questionOrder,
        });
        this.socket.send(initData);
        console.log("已发送初始化数据:", initData);
      }
    },
    connectWebSocket() {
      if (!this.socket) {
        this.socket = new WebSocket("ws://localhost:8088/rtasr");
        this.socket.onopen = () => {
          console.log("WebSocket 连接已建立");
          this.isConnected = true;
          this.sendInitData(); // 修改为发送初始化数据
        };
        this.socket.onmessage = (message) => {
          console.log("收到服务器返回结果：", message.data);
          this.processServerMessage(message.data);
          // 可在此处处理识别结果，例如更新页面显示
        };
        this.socket.onerror = (error) => {
          console.error("WebSocket 错误：", error);
        };
        this.socket.onclose = () => {
          console.log("WebSocket 连接关闭");
          this.isConnected = false;
          this.socket = null;
        };
      }
    },
    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({
          audio: {
            sampleRate: 16000, // 请求16K采样率
            channelCount: 1, // 单声道
          },
        });

        const audioContext = new (window.AudioContext || window.webkitAudioContext)({
          sampleRate: 16000, // 设置音频上下文采样率
        });

        const source = audioContext.createMediaStreamSource(stream);

        // 创建音频处理节点
        this.processor = audioContext.createScriptProcessor(1024, 1, 1);

        this.processor.onaudioprocess = (e) => {
          const inputData = e.inputBuffer.getChannelData(0);
          const pcmData = this.float32ToInt16(inputData);

          // 分片处理
          for (let i = 0; i < pcmData.length; i++) {
            this.audioBuffer[this.bufferIndex++] = pcmData[i];
            if (this.bufferIndex === 1280) {
              this.sendAudioViaWebSocket(this.audioBuffer.buffer);
              this.bufferIndex = 0;
            }
          }
        };
        source.connect(this.processor);
        this.processor.connect(audioContext.destination);
        this.isRecording = true;
      } catch (error) {
        console.error("获取麦克风权限失败：", error);
      }
    },

    // 浮点数转16位PCM
    float32ToInt16(buffer) {
      const length = buffer.length;
      const bytes = new Uint8Array(length * 2);
      for (let i = 0; i < length; i++) {
        const s = Math.max(-1, Math.min(1, buffer[i]));
        const short = s < 0 ? s * 0x8000 : s * 0x7fff;
        bytes[i * 2] = short & 0xff;
        bytes[i * 2 + 1] = (short >> 8) & 0xff;
      }
      return bytes;
    },
    async stopRecording() {
      if (this.processor) {
        this.processor.disconnect();
        this.audioContext?.close();
        if (this.bufferIndex > 0) {
          this.sendAudioViaWebSocket(this.audioBuffer.slice(0, this.bufferIndex).buffer);
        }
        this.sendEndMarker();
        this.bufferIndex = 0;
        this.isRecording = false;

        // 新增：等待1秒后关闭连接
        await new Promise((resolve) => setTimeout(resolve, 1000));
        this.closeWebSocket();
      }
    },
    sendEndMarker() {
      if (this.socket?.readyState === WebSocket.OPEN) {
        // 构建结构化结束标识
        const endMessage = JSON.stringify({ end: true });
        const encoder = new TextEncoder();
        const binaryData = encoder.encode(endMessage);

        this.socket.send(binaryData);
        console.log("已发送二进制结束标识", binaryData);
      }
    },
    sendAudioViaWebSocket(arrayBuffer) {
      if (this.socket?.readyState === WebSocket.OPEN) {
        this.socket.send(arrayBuffer);
      }
    },
    closeWebSocket() {
      if (this.socket) {
        // 发送纯文本 END 的二进制
        if (this.socket.readyState === WebSocket.OPEN) {
          const binaryEnd = new TextEncoder().encode("END"); // 纯字符串
          this.socket.send(binaryEnd);
          console.log("已发送连接关闭标识");
        }
        // 关闭连接
        this.socket.close();
        this.isConnected = false;
        this.socket = null;

        // 传递题目完成状态给interview页面
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.emit("questionCompleted", {
          questionId: this.questionOrder,
          completed: true, // 明确传递完成状态
        });

        uni.navigateBack({
          delta: 1,
          success: () => {
            console.log("返回interview页面");
          },
        });
      }
    },
    // 新增：处理服务器消息的方法
    processServerMessage(data) {
      try {
        // 尝试解析JSON格式的消息
        const parsedData = JSON.parse(data);
        this.serverMessage = JSON.stringify(parsedData, null, 2);
      } catch (e) {
        // 如果不是JSON格式，直接存储原始消息
        this.serverMessage = data;
      }

      // 过滤掉"doing"消息并更新显示
      if (!this.serverMessage.includes("doing")) {
        this.filteredServerMessage = this.serverMessage;
      }

      console.log("收到服务器返回结果：", this.serverMessage);
    },
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close(); // 组件销毁时关闭 WebSocket 连接
    }
  },
};
</script>

<style>
/* 添加问题内容样式 */
.question-context {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 15px;
  white-space: pre-wrap;
}
</style>
